package com.cyan.note.service.manager.impl;

import com.cyan.note.common.ApiResult;
import com.cyan.note.common.PageResult;
import com.cyan.note.common.ResultCode;
import com.cyan.note.dto.manager.order.*;
import com.cyan.note.entity.*;
import com.cyan.note.mapper.*;
import com.cyan.note.service.manager.ManagerOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 店长端-订单管理服务实现类
 * 
 * @author ZhangzhenYu
 * @since 2025-01-15
 */
@Service
@Slf4j
public class ManagerOrderServiceImpl implements ManagerOrderService {

    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private OrderWorkerMapper orderWorkerMapper;
    
    @Autowired
    private CustomerMapper customerMapper;
    
    @Autowired
    private WorkerMapper workerMapper;
    
    @Autowired
    private ServiceMapper serviceMapper;
    
    @Autowired
    private OrderLogMapper orderLogMapper;

    @Override
    public ApiResult<PageResult<OrderListDTO>> getOrderList(Long shopId, OrderQueryDTO query) {
        try {
            // 构建查询条件
            Map<String, Object> params = buildOrderQueryParams(shopId, query);
            
            // 查询总数
            Long total = orderMapper.countByCondition(params);
            
            // 查询数据
            List<OrderListDTO> records = new ArrayList<>();
            if (total > 0) {
                // 计算分页参数
                Long offset = (query.getCurrent() - 1) * query.getSize();
                params.put("offset", offset);
                params.put("limit", query.getSize());
                
                // 查询订单列表
                List<Order> orders = orderMapper.selectByCondition(params);
                records = convertToOrderListDTO(orders);
            }
            
            // 构建分页结果
            PageResult<OrderListDTO> pageResult = new PageResult<>();
            pageResult.setRecords(records);
            pageResult.setTotal(total);
            pageResult.setCurrent(query.getCurrent());
            pageResult.setSize(query.getSize());
            pageResult.setPages((total + query.getSize() - 1) / query.getSize());
            
            return ApiResult.success(pageResult);
        } catch (Exception e) {
            log.error("获取订单列表失败", e);
            return ApiResult.error(ResultCode.ERROR, "获取订单列表失败");
        }
    }

    @Override
    public ApiResult<OrderDetailDTO> getOrderDetail(Long shopId, Long orderId) {
        try {
            Order order = orderMapper.selectByIdAndShop(orderId, shopId);
            if (order == null) {
                return ApiResult.error(ResultCode.NOT_FOUND, "订单不存在");
            }
            
            OrderDetailDTO detail = convertToOrderDetailDTO(order);
            return ApiResult.success(detail);
        } catch (Exception e) {
            log.error("获取订单详情失败", e);
            return ApiResult.error(ResultCode.ERROR, "获取订单详情失败");
        }
    }

    @Override
    @Transactional
    public ApiResult<Long> createOrder(Long shopId, OrderCreateDTO orderCreateDTO, Long operatorId) {
        try {
            // 验证客户信息
            Customer customer = validateOrCreateCustomer(shopId, orderCreateDTO, operatorId);
            
            // 验证服务信息
            com.cyan.note.entity.Service service = serviceMapper.selectByIdAndShop(orderCreateDTO.getServiceId(), shopId);
            if (service == null) {
                return ApiResult.error(ResultCode.NOT_FOUND, "服务不存在");
            }
            
            // 创建订单
            Order order = buildOrder(shopId, orderCreateDTO, customer, service, operatorId);
            orderMapper.insert(order);
            
            // 记录订单日志
            recordOrderLog(order.getId(), "CREATE", "创建订单", operatorId, "手动创建订单");
            
            return ApiResult.success(order.getId());
        } catch (Exception e) {
            log.error("创建订单失败", e);
            return ApiResult.error(ResultCode.ERROR, "创建订单失败");
        }
    }

    @Override
    @Transactional
    public ApiResult<Void> assignOrder(Long shopId, Long orderId, OrderAssignDTO orderAssignDTO, Long operatorId) {
        try {
            Order order = orderMapper.selectByIdAndShop(orderId, shopId);
            if (order == null) {
                return ApiResult.error(ResultCode.NOT_FOUND, "订单不存在");
            }
            
            if (!"PENDING".equals(order.getStatus())) {
                return ApiResult.error(ResultCode.OPERATION_FAILED, "订单状态不允许分配");
            }
            
            // 验证打手可用性
            for (OrderAssignDTO.WorkerAssignInfo workerInfo : orderAssignDTO.getWorkers()) {
                Worker worker = workerMapper.selectByIdAndShop(workerInfo.getWorkerId(), shopId);
                if (worker == null || !"ACTIVE".equals(worker.getAccountStatus())) {
                    return ApiResult.error(ResultCode.OPERATION_FAILED, "打手不可用");
                }
            }
            
            // 删除现有分配
            orderWorkerMapper.deleteByOrderId(orderId);
            
            // 创建新分配
            for (OrderAssignDTO.WorkerAssignInfo workerInfo : orderAssignDTO.getWorkers()) {
                OrderWorker orderWorker = new OrderWorker();
                orderWorker.setOrderId(orderId);
                orderWorker.setWorkerId(workerInfo.getWorkerId());
                orderWorker.setCommissionAmount(workerInfo.getCommissionAmount());
                orderWorker.setCommissionRate(workerInfo.getCommissionRate());
                orderWorker.setRoleType(workerInfo.getRole());
                orderWorker.setAcceptedAt(LocalDateTime.now());
                orderWorker.setStatus(OrderWorker.Status.ASSIGNED);
                orderWorker.setCreatedAt(LocalDateTime.now());
                orderWorker.setUpdatedAt(LocalDateTime.now());
                orderWorkerMapper.insert(orderWorker);
            }
            
            // 更新订单状态
            order.setStatus("ASSIGNED");
            order.setUpdatedAt(LocalDateTime.now());
            orderMapper.updateById(order);
            
            // 记录日志
            recordOrderLog(orderId, "ASSIGN", "分配订单", operatorId, 
                "分配给打手: " + orderAssignDTO.getWorkers().size() + "人");
            
            return ApiResult.success();
        } catch (Exception e) {
            log.error("分配订单失败", e);
            return ApiResult.error(ResultCode.ERROR, "分配订单失败");
        }
    }

    @Override
    @Transactional
    public ApiResult<Void> completeOrder(Long shopId, Long orderId, OrderCompleteDTO orderCompleteDTO, Long operatorId) {
        try {
            Order order = orderMapper.selectByIdAndShop(orderId, shopId);
            if (order == null) {
                return ApiResult.error(ResultCode.NOT_FOUND, "订单不存在");
            }
            
            if (!"IN_PROGRESS".equals(order.getStatus())) {
                return ApiResult.error(ResultCode.OPERATION_FAILED, "订单状态不允许结单");
            }
            
            // 更新订单信息
            if (orderCompleteDTO != null) {
                if (orderCompleteDTO.getActualEndTime() != null) {
                    order.setActualEndTime(orderCompleteDTO.getActualEndTime());
                } else {
                    order.setActualEndTime(LocalDateTime.now());
                }
                
                if (orderCompleteDTO.getActualAmount() != null) {
                    order.setTotalAmount(orderCompleteDTO.getActualAmount());
                }
                
                if (orderCompleteDTO.getCompleteRemark() != null) {
                    order.setInternalNotes((order.getInternalNotes() != null ? order.getInternalNotes() : "") + "; 结单备注: " + orderCompleteDTO.getCompleteRemark());
                }
            } else {
                order.setActualEndTime(LocalDateTime.now());
            }
            
            order.setStatus("COMPLETED");
            order.setUpdatedAt(LocalDateTime.now());
            orderMapper.updateById(order);
            
            // 记录日志
            recordOrderLog(orderId, "COMPLETE", "手动结单", operatorId, "店长手动结单");
            
            return ApiResult.success();
        } catch (Exception e) {
            log.error("结单失败", e);
            return ApiResult.error(ResultCode.ERROR, "结单失败");
        }
    }

    @Override
    @Transactional
    public ApiResult<Void> confirmPayment(Long shopId, Long orderId, OrderPaymentDTO orderPaymentDTO, Long operatorId) {
        try {
            Order order = orderMapper.selectByIdAndShop(orderId, shopId);
            if (order == null) {
                return ApiResult.error(ResultCode.NOT_FOUND, "订单不存在");
            }
            
            if (!"COMPLETED".equals(order.getStatus())) {
                return ApiResult.error(ResultCode.OPERATION_FAILED, "订单状态不允许确认收款");
            }
            
            // 更新收款信息
            order.setPaidAmount(orderPaymentDTO.getReceivedAmount());
            order.setPaymentStatus(Order.PaymentStatus.PAID);
            order.setStatus("PAID");
            order.setUpdatedAt(LocalDateTime.now());
            
            if (orderPaymentDTO.getPaymentRemark() != null) {
                order.setInternalNotes((order.getInternalNotes() != null ? order.getInternalNotes() : "") + "; 收款备注: " + orderPaymentDTO.getPaymentRemark());
            }
            
            orderMapper.updateById(order);
            
            // 记录日志
            recordOrderLog(orderId, "PAYMENT", "确认收款", operatorId, 
                "收款金额: " + orderPaymentDTO.getReceivedAmount());
            
            return ApiResult.success();
        } catch (Exception e) {
            log.error("确认收款失败", e);
            return ApiResult.error(ResultCode.ERROR, "确认收款失败");
        }
    }

    @Override
    @Transactional
    public ApiResult<Void> cancelOrder(Long shopId, Long orderId, OrderCancelDTO orderCancelDTO, Long operatorId) {
        try {
            Order order = orderMapper.selectByIdAndShop(orderId, shopId);
            if (order == null) {
                return ApiResult.error(ResultCode.NOT_FOUND, "订单不存在");
            }
            
            // 更新订单状态
            order.setStatus("CANCELLED");
            order.setCancelReason(orderCancelDTO.getCancelReason());
            order.setUpdatedAt(LocalDateTime.now());
            
            String cancelInfo = "取消原因: " + orderCancelDTO.getCancelReason();
            if (orderCancelDTO.getCancelDescription() != null) {
                cancelInfo += "; 详细说明: " + orderCancelDTO.getCancelDescription();
            }
            order.setInternalNotes((order.getInternalNotes() != null ? order.getInternalNotes() : "") + "; " + cancelInfo);
            
            orderMapper.updateById(order);
            
            // 记录日志
            recordOrderLog(orderId, "CANCEL", "炸单处理", operatorId, cancelInfo);
            
            return ApiResult.success();
        } catch (Exception e) {
            log.error("取消订单失败", e);
            return ApiResult.error(ResultCode.ERROR, "取消订单失败");
        }
    }

    @Override
    @Transactional
    public ApiResult<Void> reassignOrder(Long shopId, Long orderId, OrderAssignDTO orderAssignDTO, Long operatorId) {
        try {
            Order order = orderMapper.selectByIdAndShop(orderId, shopId);
            if (order == null) {
                return ApiResult.error(ResultCode.NOT_FOUND, "订单不存在");
            }
            
            if (!"CANCELLED".equals(order.getStatus())) {
                return ApiResult.error(ResultCode.OPERATION_FAILED, "订单状态不允许重新分配");
            }
            
            // 重新分配订单
            ApiResult<Void> assignResult = assignOrder(shopId, orderId, orderAssignDTO, operatorId);
            if (!assignResult.isSuccess()) {
                return assignResult;
            }
            
            // 更新订单状态为待开始
            order.setStatus("PENDING");
            order.setUpdatedAt(LocalDateTime.now());
            orderMapper.updateById(order);
            
            // 记录日志
            recordOrderLog(orderId, "REASSIGN", "重新分配", operatorId, "炸单后重新分配");
            
            return ApiResult.success();
        } catch (Exception e) {
            log.error("重新分配订单失败", e);
            return ApiResult.error(ResultCode.ERROR, "重新分配订单失败");
        }
    }

    @Override
    public ApiResult<List<AvailableWorkerForOrderDTO>> getAvailableWorkers(Long shopId, String orderType, String startTime) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("shopId", shopId);
            params.put("orderType", orderType);
            params.put("startTime", startTime);
            
            List<AvailableWorkerForOrderDTO> workers = workerMapper.selectAvailableWorkersForOrder(params);
            return ApiResult.success(workers);
        } catch (Exception e) {
            log.error("获取可分配打手失败", e);
            return ApiResult.error(ResultCode.ERROR, "获取可分配打手失败");
        }
    }

    @Override
    public ApiResult<OrderStatusStatsDTO> getOrderStatusStats(Long shopId, String startDate, String endDate) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("shopId", shopId);
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            
            OrderStatusStatsDTO stats = orderMapper.selectOrderStatusStats(params);
            return ApiResult.success(stats);
        } catch (Exception e) {
            log.error("获取订单状态统计失败", e);
            return ApiResult.error(ResultCode.ERROR, "获取订单状态统计失败");
        }
    }

    @Override
    @Transactional
    public ApiResult<Void> batchOperateOrders(Long shopId, OrderBatchOperateDTO batchOperateDTO, Long operatorId) {
        try {
            for (Long orderId : batchOperateDTO.getOrderIds()) {
                Order order = orderMapper.selectByIdAndShop(orderId, shopId);
                if (order == null) {
                    continue;
                }
                
                // 根据操作类型执行不同操作
                switch (batchOperateDTO.getOperationType()) {
                    case "CANCEL":
                        // 批量取消
                        order.setStatus(Order.Status.CANCELLED);
                        order.setCancelReason("批量取消");
                        break;
                    case "CONFIRM_PAYMENT":
                        // 批量确认收款
                        if (Order.Status.COMPLETED.equals(order.getStatus())) {
                            order.setStatus(Order.Status.PAID);
                            order.setPaymentStatus(Order.PaymentStatus.PAID);
                        }
                        break;
                }
                
                order.setUpdatedAt(LocalDateTime.now());
                orderMapper.updateById(order);
                
                // 记录日志
                recordOrderLog(orderId, batchOperateDTO.getOperationType(), "批量操作", operatorId, 
                    batchOperateDTO.getOperationRemark());
            }
            
            return ApiResult.success();
        } catch (Exception e) {
            log.error("批量操作订单失败", e);
            return ApiResult.error(ResultCode.ERROR, "批量操作订单失败");
        }
    }

    @Override
    public ApiResult<String> exportOrders(Long shopId, String status, String startDate, String endDate, String format) {
        try {
            // 这里应该实现具体的导出逻辑
            // 返回导出文件的URL或文件ID
            String exportUrl = "/api/files/orders_export_" + System.currentTimeMillis() + "." + format;
            return ApiResult.success(exportUrl);
        } catch (Exception e) {
            log.error("导出订单失败", e);
            return ApiResult.error(ResultCode.ERROR, "导出订单失败");
        }
    }

    // 私有辅助方法

    private Map<String, Object> buildOrderQueryParams(Long shopId, OrderQueryDTO query) {
        Map<String, Object> params = new HashMap<>();
        params.put("shopId", shopId);
        
        if (query.getStatus() != null && !query.getStatus().isEmpty()) {
            params.put("status", query.getStatus());
        }
        if (query.getOrderType() != null && !query.getOrderType().isEmpty()) {
            params.put("orderType", query.getOrderType());
        }
        if (query.getOrderSource() != null && !query.getOrderSource().isEmpty()) {
            params.put("orderSource", query.getOrderSource());
        }
        if (query.getCustomerName() != null && !query.getCustomerName().isEmpty()) {
            params.put("customerName", "%" + query.getCustomerName() + "%");
        }
        if (query.getWorkerName() != null && !query.getWorkerName().isEmpty()) {
            params.put("workerName", "%" + query.getWorkerName() + "%");
        }
        if (query.getStartDate() != null && !query.getStartDate().isEmpty()) {
            params.put("startDate", query.getStartDate());
        }
        if (query.getEndDate() != null && !query.getEndDate().isEmpty()) {
            params.put("endDate", query.getEndDate());
        }
        
        return params;
    }

    private List<OrderListDTO> convertToOrderListDTO(List<Order> orders) {
        return orders.stream().map(this::convertToOrderListDTO).collect(Collectors.toList());
    }

    private OrderListDTO convertToOrderListDTO(Order order) {
        OrderListDTO dto = new OrderListDTO();
        dto.setId(order.getId());
        dto.setOrderNumber(order.getOrderNo());
        dto.setOrderType(order.getOrderType());
        dto.setOrderTypeName(getOrderTypeName(order.getOrderType()));
        dto.setStatus(order.getStatus());
        dto.setStatusName(getOrderStatusName(order.getStatus()));
        dto.setOrderSource(order.getOrderSource());
        dto.setOrderSourceName(getOrderSourceName(order.getOrderSource()));
        // 需要通过客户ID查询客户信息
        dto.setServiceDuration(order.getDurationHours() != null ? order.getDurationHours().intValue() : null);
        dto.setOrderAmount(order.getTotalAmount());
        dto.setActualAmount(order.getTotalAmount());
        dto.setStartTime(order.getActualStartTime());
        dto.setEndTime(order.getActualEndTime());
        dto.setCreatedAt(order.getCreatedAt());
        dto.setRemark(order.getInternalNotes());
        
        // 获取打手信息
        List<OrderWorker> orderWorkers = orderWorkerMapper.selectByOrderId(order.getId());
        List<OrderListDTO.OrderWorkerInfo> workerInfos = orderWorkers.stream().map(ow -> {
            OrderListDTO.OrderWorkerInfo info = new OrderListDTO.OrderWorkerInfo();
            Worker worker = workerMapper.selectById(ow.getWorkerId());
            if (worker != null) {
                info.setWorkerId(worker.getId());
                info.setWorkerName(worker.getNickname());
                info.setWorkerPhone(worker.getPhone());
            }
            info.setCommissionAmount(ow.getCommissionAmount());
            info.setCommissionRate(ow.getCommissionRate());
            return info;
        }).collect(Collectors.toList());
        dto.setWorkers(workerInfos);
        
        return dto;
    }

    private OrderDetailDTO convertToOrderDetailDTO(Order order) {
        OrderDetailDTO detail = new OrderDetailDTO();
        detail.setId(order.getId());
        detail.setOrderNumber(order.getOrderNo());
        detail.setOrderType(order.getOrderType());
        detail.setOrderTypeName(getOrderTypeName(order.getOrderType()));
        detail.setStatus(order.getStatus());
        detail.setStatusName(getOrderStatusName(order.getStatus()));
        detail.setOrderSource(order.getOrderSource());
        detail.setOrderSourceName(getOrderSourceName(order.getOrderSource()));
        detail.setRemark(order.getInternalNotes());
        detail.setCreatedAt(order.getCreatedAt());
        detail.setUpdatedAt(order.getUpdatedAt());
        
        // 客户信息
        OrderDetailDTO.CustomerInfo customerInfo = new OrderDetailDTO.CustomerInfo();
        customerInfo.setCustomerId(order.getCustomerId());
        // 需要通过客户ID查询客户详细信息
        detail.setCustomer(customerInfo);
        
        // 服务信息
        OrderDetailDTO.ServiceInfo serviceInfo = new OrderDetailDTO.ServiceInfo();
        serviceInfo.setServiceId(order.getServiceId());
        serviceInfo.setServiceDuration(order.getDurationHours() != null ? order.getDurationHours().intValue() : null);
        detail.setService(serviceInfo);
        
        // 金额信息
        OrderDetailDTO.AmountInfo amountInfo = new OrderDetailDTO.AmountInfo();
        amountInfo.setOrderAmount(order.getTotalAmount());
        amountInfo.setActualAmount(order.getTotalAmount());
        amountInfo.setDiscountAmount(order.getDiscountAmount());
        amountInfo.setPaymentStatus(order.getPaymentStatus());
        detail.setAmount(amountInfo);
        
        // 时间信息
        OrderDetailDTO.TimeInfo timeInfo = new OrderDetailDTO.TimeInfo();
        timeInfo.setAppointmentTime(order.getScheduledStartTime());
        timeInfo.setStartTime(order.getActualStartTime());
        timeInfo.setEndTime(order.getActualEndTime());
        timeInfo.setPlannedDuration(order.getDurationHours() != null ? order.getDurationHours().intValue() : null);
        detail.setTime(timeInfo);
        
        // 打手信息
        List<OrderWorker> orderWorkers = orderWorkerMapper.selectByOrderId(order.getId());
        List<OrderDetailDTO.WorkerInfo> workerInfos = orderWorkers.stream().map(ow -> {
            OrderDetailDTO.WorkerInfo info = new OrderDetailDTO.WorkerInfo();
            Worker worker = workerMapper.selectById(ow.getWorkerId());
            if (worker != null) {
                info.setWorkerId(worker.getId());
                info.setWorkerName(worker.getNickname());
                info.setWorkerPhone(worker.getPhone());
                info.setWorkerLevel(worker.getLevel());
            }
            info.setCommissionAmount(ow.getCommissionAmount());
            info.setCommissionRate(ow.getCommissionRate());
            info.setAssignTime(ow.getAcceptedAt() != null ? ow.getAcceptedAt().toString() : null);
            info.setStatus(ow.getStatus());
            return info;
        }).collect(Collectors.toList());
        detail.setWorkers(workerInfos);
        
        // 订单日志
        List<OrderLog> orderLogs = orderLogMapper.selectByOrderId(order.getId());
        List<OrderDetailDTO.OrderLogInfo> logInfos = orderLogs.stream().map(log -> {
            OrderDetailDTO.OrderLogInfo info = new OrderDetailDTO.OrderLogInfo();
            info.setAction(log.getAction());
            info.setActionName(getActionName(log.getAction()));
            info.setOperatorName(log.getOperatorName());
            info.setDescription(log.getDescription());
            info.setOperateTime(log.getCreatedAt());
            return info;
        }).collect(Collectors.toList());
        detail.setLogs(logInfos);
        
        return detail;
    }

    private Customer validateOrCreateCustomer(Long shopId, OrderCreateDTO orderCreateDTO, Long operatorId) {
        Customer customer = null;
        
        if (orderCreateDTO.getCustomerId() != null) {
            customer = customerMapper.selectByIdAndShop(orderCreateDTO.getCustomerId(), shopId);
        }
        
        if (customer == null) {
            // 根据手机号查找客户
            customer = customerMapper.selectByPhoneAndShop(orderCreateDTO.getCustomerPhone(), shopId);
        }
        
        if (customer == null) {
            // 创建新客户
            customer = new Customer();
            customer.setShopId(shopId);
            customer.setNickname(orderCreateDTO.getCustomerName());
            customer.setPhone(orderCreateDTO.getCustomerPhone());
            customer.setAddress(orderCreateDTO.getCustomerAddress());
            customer.setLevel(Customer.Level.NEW);
            customer.setStatus(Customer.Status.NORMAL);
            customer.setCreatedAt(LocalDateTime.now());
            customer.setUpdatedAt(LocalDateTime.now());
            customerMapper.insert(customer);
        }
        
        return customer;
    }

    private Order buildOrder(Long shopId, OrderCreateDTO orderCreateDTO, Customer customer, 
            com.cyan.note.entity.Service service, Long operatorId) {
        Order order = new Order();
        order.setShopId(shopId);
        order.setOrderNo(generateOrderNumber());
        order.setOrderType(orderCreateDTO.getOrderType());
        order.setOrderSource(orderCreateDTO.getOrderSource());
        order.setCustomerId(customer.getId());
        order.setServiceId(service.getId());
        order.setTotalAmount(orderCreateDTO.getOrderAmount());
        order.setDiscountAmount(orderCreateDTO.getDiscountAmount());
        order.setDurationHours(BigDecimal.valueOf(orderCreateDTO.getServiceDuration()));
        order.setScheduledStartTime(orderCreateDTO.getAppointmentTime());
        order.setStatus(Order.Status.PENDING);
        order.setPaymentStatus(Order.PaymentStatus.UNPAID);
        order.setInternalNotes(orderCreateDTO.getRemark());
        order.setCreatedBy(operatorId);
        order.setCreatedAt(LocalDateTime.now());
        order.setUpdatedAt(LocalDateTime.now());
        
        return order;
    }

    private void recordOrderLog(Long orderId, String action, String actionName, Long operatorId, String description) {
        OrderLog log = new OrderLog();
        log.setOrderId(orderId);
        log.setAction(action);
        log.setOperatorId(operatorId);
        log.setOperatorName("店长");  // 这里应该从用户表获取真实姓名
        log.setDescription(description);
        log.setCreatedAt(LocalDateTime.now());
        orderLogMapper.insert(log);
    }

    private String generateOrderNumber() {
        return "ORD" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + 
            String.format("%03d", new Random().nextInt(1000));
    }

    private String getOrderTypeName(String orderType) {
        switch (orderType) {
            case "hourly": return "陪玩单";
            case "fixed": return "护航单";
            default: return orderType;
        }
    }

    private String getOrderStatusName(String status) {
        switch (status) {
            case "PENDING": return "待开始";
            case "ASSIGNED": return "已分配";
            case "IN_PROGRESS": return "进行中";
            case "COMPLETED": return "未结账";
            case "PAID": return "已付款";
            case "CANCELLED": return "已取消";
            default: return status;
        }
    }

    private String getOrderSourceName(String orderSource) {
        switch (orderSource) {
            case "manual": return "手动下单";
            case "wechat_miniprogram": return "微信小程序";
            case "h5_website": return "H5网站";
            default: return orderSource;
        }
    }

    private String getActionName(String action) {
        switch (action) {
            case "CREATE": return "创建订单";
            case "ASSIGN": return "分配订单";
            case "START": return "开始服务";
            case "COMPLETE": return "完成服务";
            case "PAYMENT": return "确认收款";
            case "CANCEL": return "取消订单";
            case "REASSIGN": return "重新分配";
            default: return action;
        }
    }
}